/**
 * Copyright by www.tienon.com
 * All right reserved.
 */
package com.app.oasystem.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

public class SessionUtil {

	static ThreadLocal<HttpServletRequest> threadLocalRequest = new ThreadLocal<HttpServletRequest>();
	static ThreadLocal<HttpServletResponse> threadLocalResponse = new ThreadLocal<HttpServletResponse>();
	static ThreadLocal<Map<String, Object>> threadLocalMap = new ThreadLocal<Map<String, Object>>();

	public static <T> T getObjBySessionKey(String sessionKey, Class<T> clazz) {
		return clazz.cast(getSession().getAttribute(sessionKey));
	}

	public static void setObjBySessionKey(String sessionKey, Object obj) {
		getSession().setAttribute(sessionKey, obj);
	}

	public static HttpSession getSession() {
		return threadLocalRequest.get().getSession();
	}

	public static void setRequest(HttpServletRequest request) {
		threadLocalRequest.set(request);
	}

	public static HttpServletRequest getRequest() {
		return threadLocalRequest.get();
	}

	public static void setResponse(HttpServletResponse response) {
		threadLocalResponse.set(response);
	}

	public static HttpServletResponse getResponse() {
		return threadLocalResponse.get();
	}

	public static void putVariable(String name, Object variables) {
		if (threadLocalMap.get() == null) {
			Map<String, Object> map = new HashMap<String, Object>(16);
			map.put(name, variables);
			threadLocalMap.set(map);
		} else {
			threadLocalMap.get().put(name, variables);
		}
	}

	public static Object getVariable(String name) {
		if (threadLocalMap.get() == null) {
			return null;
		}
		return threadLocalMap.get().get(name);
	}

	public static void removeThreadLocalRequest() {
		threadLocalRequest.remove();
	}

	public static void removeThreadLocalResponse() {
		threadLocalResponse.remove();
	}

	public static void removeThreadLocalMap() {
		threadLocalMap.remove();
	}
}
